/**
 * 周次选择器组件
 */

'use client';

import React, { useState, useRef } from 'react';
import { createPortal } from 'react-dom';
import { ChevronDown } from 'lucide-react';
import { clsx } from 'clsx';

export interface WeekSelectorProps {
  /** 是否打开 */
  isOpen: boolean;
  /** 打开状态变化回调 */
  onOpenChange: (isOpen: boolean) => void;
  /** 当前周次 */
  currentWeek: number;
  /** 可选择的周次列表 */
  availableWeeks: number[];
  /** 周次变化回调 */
  onWeekChange: (week: number) => void;
  /** 自定义类名 */
  className?: string;
}

export const WeekSelector: React.FC<WeekSelectorProps> = ({
  isOpen,
  onOpenChange,
  currentWeek,
  availableWeeks,
  onWeekChange,
  className
}) => {
  const buttonRef = useRef<HTMLButtonElement>(null);

  const handleWeekSelect = (week: number) => {
    onWeekChange(week);
    onOpenChange(false);
  };

  const toggleOpen = () => {
    onOpenChange(!isOpen);
  };

  return (
    <div className={clsx('relative', className)}>
      {/* 触发按钮 */}
      <button
        ref={buttonRef}
        className="flex items-center gap-2 px-4 py-2 bg-blue-500 hover:bg-blue-600 rounded-lg text-white font-medium transition-colors shadow-md"
        onClick={toggleOpen}
      >
        <span>第{currentWeek}周</span>
        <ChevronDown className={clsx("w-4 h-4 transition-transform", isOpen && "rotate-180")} />
      </button>

      {/* 下拉列表 */}
      {isOpen && (
        <>
          {/* 背景遮罩 (Portal 渲染，覆盖全屏) */}
          {createPortal(
            <div
              className="fixed inset-0 z-[100]"
              onClick={() => onOpenChange(false)}
            />,
            typeof document !== 'undefined' ? document.body : (null as unknown as Element)
          )}
          
          {/* 选择器面板 (Portal 渲染) */}
          {createPortal(
            <div 
              className="absolute top-full left-0 mt-2 w-48 max-h-64 bg-white rounded-lg shadow-lg border overflow-hidden z-[101]"
              // 我们需要手动计算位置，因为 Portal 脱离了正常的文档流
              style={{
                top: buttonRef.current?.getBoundingClientRect().bottom ?? 0 + 8,
                left: buttonRef.current?.getBoundingClientRect().left ?? 0
              }}
            >
              <div className="overflow-y-auto max-h-64">
                {availableWeeks.map((week) => (
                  <button
                    key={week}
                    className={clsx(
                      'w-full px-4 py-3 text-left text-black hover:bg-blue-50 transition-colors border-b border-gray-100 last:border-b-0',
                      week === currentWeek && 'bg-blue-500 text-white hover:bg-blue-600'
                    )}
                    onClick={() => handleWeekSelect(week)}
                  >
                    第{week}周
                  </button>
                ))}
              </div>
            </div>,
            typeof document !== 'undefined' ? document.body : (null as unknown as Element)
          )}
        </>
      )}
    </div>
  );
};
